package com.iwithlong.utils;

import com.iwithlong.entity.Area;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取行政区域
 * <p>
 * User: TJM
 * Date: 2017/10/12 10:10
 * version $Id: ReadAreaUtils.java, v 0.1  10:10 Exp $
 */
public class ReadAreaUtils {

	/**省级*/
	private static List<Area> provinceList ;

	/**市级*/
	private static List<Area> townList ;

	/**县级*/
	private static List<Area> countyList ;

	private static Map<String,List<Area>> map;


	public static Map<String,List<Area>> getAreaData(){
		String str=ReadAreaUtils.class.getClassLoader ().getResource ("data/全国行政区划代码201607.txt").getPath ();
		try {
			str = URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}
		return getAreaData(str);
	}


	public static Map<String,List<Area>> getAreaData(String path){
		if (CollectionUtils.isEmpty (map)) {
			ReadAllArea(path);
			map = new HashMap<> ();
			map.put("provinceList", provinceList);
			map.put("townList", townList);
			map.put("countyList",  countyList);
		}
		return map ;
	}


	private static void ReadAllArea(String path){

		 provinceList = new ArrayList<>();
		 townList = new ArrayList<>();
		 countyList = new ArrayList<>();


		File file = new File(path);

		Area city=new Area ();
		Area county=new Area ();
		try {
			FileInputStream in=new FileInputStream (file);

			//读取文件的每一行
			List<String> strings = IOUtils.readLines (in,"UTF-8");

			for (String line : strings) {
				String[] data = cutString(line);

				if (data==null){
					continue;
				}

				//处理读取的文件记录
				if(isProvince(data[0])){
					Area area = new Area(data[0], data[1], 0, "0");
					provinceList.add (area);
					city=area;
				}else if(isTown(data[0])){
					Area area = new Area(data[0], data[1], 1);
					county=area;
					city.addChildren (area);
					townList.add (area);
				}else{
					Area area = new Area(data[0], data[1], 2);
					county.addChildren (area);
					countyList.add (area);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//字符分割
	private static  String[] cutString(String line){

		if (StringUtils.isNotBlank (line)) {
			String code=line.substring(0, 6);
			String lastStr = line.substring(7, line.length());
			String name = lastStr.substring(lastStr.indexOf("\t")+1, lastStr.length ());
			return new String []{code,name};
		}
		return null;
	}

	//判断是否省或者直辖市
	private static  boolean isProvince(String code){
		String last = code.substring(2);
		return "0000".equalsIgnoreCase (last);
	}
	//判断是否地级市
	private static  boolean isTown(String code){
		String last = code.substring(4);
		return "00".equalsIgnoreCase (last);
	}


}
